<?php

namespace App\Http\Controllers\Mini;

use App\Models\Ads;
use App\Models\Collections;
use App\Models\Footprints;
use App\Models\Goods;
use App\Models\GoodsCategorys;
use App\Models\GoodsEvaluates;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class GoodsController extends Controller
{
    /**
     * 商品分类
     * @route api.goods.goodsCate
     */
    public function goodsCate(Request $request){
        try{
            $lists = GoodsCategorys::getCascaderList();
            $fields = ['id','title','thumb','price','salenum','cate_id','cate_pid','type'];
            foreach ($lists as $k=>$v){//获取分类下的热门商品、最新商品
                $lists[$k]['hot'] = Goods::allLists([], $fields, null, 6, 'salenum');
                $lists[$k]['new'] = Goods::allLists([], $fields, null, 6, 'created_at');
                foreach ($lists[$k]['hot'] as $key=>$val){
                    $lists[$k]['hot'][$key]['salenum'] = strlen($val['salenum'])>=4 ? '999+' : $val['salenum'];
                }
                foreach ($lists[$k]['new'] as $key=>$val){
                    $lists[$k]['new'][$key]['salenum'] = strlen($val['salenum'])>=4 ? '999+' : $val['salenum'];
                }
                //获取分类下的广告
                $params = [
                    'cate_id' => $v['value'],
                    'adsense_id' => 37,
                    'status' => 1,
                    'limit' => 1,
//                    'start_at' => date('Y-m-d H:i:s'),
//                    'end_at' => date('Y-m-d H:i:s'),
                ];
                $lists[$k]['adv'] = Ads::getList($params, ['id','adsense_id','thumb','link']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 商品筛选
     * @route api.goods.goodsScreen
     */
    public function goodsScreen(Request $request){
        try{
            $lists = GoodsCategorys::getCascaderList();

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 商品列表
     * @route api.goods.goodsLists
     * @param cid_id 二级分类id
     * @param page 页码
     * @param limit 条数
     * @param sid 排序 1成交量 2好评量
     */
    public function goodsLists(Request $request){
        try{
            $cid_id = $request->post('cid_id');//二级分类id
            if (!empty($cid_id)){
                $map['cid_id'] = explode(",", $cid_id);
            }else {
                $map['cid_id'] = null;
            }
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',4);//条数
            if (empty($page) || empty($limit)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $sid = (int)$request->post('sid');//排序 1成交量 2好评量
            if ($sid == 1){
                $sort = 'salenum';
            }elseif ($sid == 2){
                $sort = 'praise';
            }else{
                $sort = 'created_at';
            }
            $fields = ['id','title','thumb','price','praise','salenum','cate_id','cate_pid','type'];
            $lists = Goods::allLists($map, $fields, $page, $limit, $sort, 'desc');
            foreach ($lists as $key=>$val){
                $lists[$key]['salenum'] = strlen($val['salenum'])>=4 ? '999+' : $val['salenum'];
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 商品详情
     * @route api.goods.goodsDetails
     * @param user_id 用户id
     * @param goods_id 商品id
     * @return is_collect 0:未收藏 1:已收藏
     */
    public function goodsDetails(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            $user_info = Users::where('id',$user_id)->where('status','<>',-1)->first();
            $goods_id = (int)$request->post('goods_id');//商品id
            if (empty($goods_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $fields = ['id','store_id','title','thumb','images','price','content','star','cate_id','cate_pid','type'];
            $lists = Goods::details(['id'=>$goods_id], $fields);

            //判断是否收藏和报名
            $lists['is_collect'] = 0;//默认未收藏
            if (!empty($user_info)){
                if ($user_info['type'] == 1){
                    $collect = Collections::where(['collect_id'=>$goods_id,'user_id'=>$user_info['id'],'type'=>3])->value('collect_id');
                    $lists['is_collect'] = empty($collect) ? 0 : 1;
                }
                //添加足迹
                $foot_arr = [
                    'user_id' => $user_info['id'],
                    'foot_id' => $goods_id,
                    'type'    => 3,
                ];
                Footprints::create($foot_arr);
            }
            Goods::where('id',$goods_id)->increment('view');//浏览量加1

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 商品评价列表
     * @route api.goods.goodsEvaluateLists
     * @param goods_id 商品id
     * @param evaluate_type 评价类型：1好评 2中评 3差评
     * @param page 页码
     * @param limit 条数
     */
    public function goodsEvaluateLists(Request $request){
        try{
            $goods_id = (int)$request->post('goods_id');//商品id
            $evaluate_type = (int)$request->post('evaluate_type');//评价类型：1好评 2中评 3差评
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',3);//条数
            if (empty($goods_id) || empty($page) || empty($limit)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $fields = ['id','user_id','user_name','user_avatar','goods_id','images','content','type','average_star','created_at'];
            $evaluates = GoodsEvaluates::allLists(['goods_id' => $goods_id,'type' => $evaluate_type], $fields, $page, $limit);
            foreach ($evaluates as $k=>$v){
                $evaluates[$k]['user_name'] = '**'.mb_substr($v['user_name'],-2,4,"utf-8");
            }

            $sum = GoodsEvaluates::counts(['goods_id'=>$goods_id]);
            $good = GoodsEvaluates::counts(['goods_id'=>$goods_id,'type'=>1]);
            $middle = GoodsEvaluates::counts(['goods_id'=>$goods_id,'type'=>2]);
            $bad = GoodsEvaluates::counts(['goods_id'=>$goods_id,'type'=>3]);

            $lists = [];
            $lists['sum'] = $sum;//评价总数
            $lists['good'] = strlen($good)>=4 ? '999+' : $good;//好评数
            $lists['middle'] = strlen($middle)>=4 ? '999+' : $middle;//中评数
            $lists['bad'] = strlen($bad)>=4 ? '999+' : $bad;//差评数
            $lists['avg_good'] = empty($sum) ? 0 : intval(round (($good/$sum)*100));//好评率
            $lists['evaluates'] = $evaluates;

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 收藏商品
     * @route api.goods.goodsCollect
     * @param user_id 用户id
     * @param collect_id 收藏内容id
     */
    public function goodsCollects(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $collect_id = (int)$request->post('collect_id');
            if (empty($collect_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->value('type');
            if (empty($userinfo)) return response()->json(["code"=>0, "msg"=>'用户不存在']);
            if ($userinfo != 1) return response()->json(["code"=>0, "msg"=>'供应商不能收藏']);
            $collect = Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>3])->value('id');
            if (empty($collect)){
                $params = [
                    'collect_id' => $collect_id,
                    'user_id' => $user_id,
                    'collect_at' => date('Y-m-d H:i:s'),
                    'type' => 3,
                ];
                Collections::create($params);
                Goods::where('id',$collect_id)->increment('collect');
                return response()->json(["code"=>1, "msg"=>'收藏成功']);
            }else {
                Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>3])->delete();
                return response()->json(["code"=>1, "msg"=>'取消收藏成功']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

}